/**
 * @name dateFormat
 * @author darcrand
 * @param {Object|Number} date 日期对象|时间戳
 * @param {String} formate 日期格式 'yyy'表示年份,'mmm'表示月份,'ddd'表示日期,'www'表示星期几,'hh'表示小时,'mm'表示分钟,'ss'表示秒
 */

function dateFormate(date, formate = 'yyy-mmm-ddd 星期www hh:mm:ss') {
  if (!date) {
    throw 'first param "date" is missing'
  } else if (!(date instanceof Date || date > 0)) {
    throw 'first param "date" should be a "object Date()" or "timeStamp"'
  }
  date = date instanceof Date ? date : new Date(date)
  const d = {
    yyy: date.getFullYear(),
    mmm: date.getMonth() + 1,
    ddd: date.getDate(),
    www: ['日', '一', '二', '三', '四', '五', '六'][date.getDay()],
    hh: date.getHours(),
    mm: date.getMinutes(),
    ss: date.getSeconds()
  }
  const zero = num => (num > 9 ? num : `0${num}`)
  let formateStr = formate
  for (const key in d) {
    if (d.hasOwnProperty(key)) {
      const reg = new RegExp(`${key}`)
      formateStr = formateStr.replace(reg, key === 'www' ? d[key] : zero(d[key]))
    }
  }
  return formateStr
}

/**
 * @name nav-to
 * @desc 模拟跳转到指定页面;可传参数
 */
function navTo(to) {
  const type = (typeof to).toLowerCase()
  const prefix = '/pages/'
  const suffix = '/main'

  let url = null
  if (type === 'string') {
    url = `${prefix}${to}${suffix}`
  } else if (type === 'object') {
    if (to.name && to.query) {
      let str = '?'
      for (const [k, v] of Object.entries(to.query)) {
        str += `${k}=${v}&`
      }
      str = str.slice(0, -1)
      url = `${prefix}${to.name}${suffix}${str}`
    } else if (to.name) {
      url = `${prefix}${to.name}${suffix}`
    }
  }
  wx.navigateTo({ url })
}

/**
 * @param {Number} num - 要处理的数值
 * @param {Object} options - 配置项
 * {
 *  {Number} count - 小数点后保留的位数
 *  {Sting} type - 小数位舍入方式,可选['round','ceil','floor']
 * }
 */
function numberFixed(num = 0, options = { count: 2, type: 'round' }) {
  const power = Math.pow(10, options.count)
  return Math[options.type](num * power) / power
}

export { dateFormate, navTo, numberFixed }
